package com.qf.controller.servlet;

import com.alibaba.fastjson.JSON;
import com.qf.dao.UserDao;
import com.qf.dao.impl.UserDaoImpl;
import com.qf.domain.*;
import com.qf.service.*;
import com.qf.service.impl.*;
import com.qf.utils.Base64Utils;
import com.qf.utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author YDW
 * projectName:shopping
 * time:2022/4/21 11:02
 * description:
 */
@WebServlet("/adminservlet")
@MultipartConfig(maxFileSize = 1024*1024*5,maxRequestSize = 1024*1024*20)
public class AdminServlet extends BaseServlet{
    AdminService adminService=new AdminServiceImpl();
    GoodsTypeService goodsTypeService=new GoodsTypeServiceImpl();
    GoodsService goodsService=new GoodsServiceImpl();
    OrderService orderService=new OrderServiceImpl();
    UserService userService=new UserServiceImpl();
    public String AdminLogin(HttpServletRequest request, HttpServletResponse response){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            return "redirect:/admin/login.jsp";
        }
        User user=adminService.adminLogin(username,password);
        if(user!=null){
            request.getSession().setAttribute("admin",user);
            return "redirect:/admin/admin.jsp";
        }else{
            return "redirect:/admin/login.jsp";
        }
    }
    public String logOut(HttpServletRequest request,HttpServletResponse response){
        //清除session
        request.getSession().removeAttribute("admin");
        return "redirect:/admin/login.jsp";
    }
    public void  getUserList(HttpServletRequest request,HttpServletResponse response) throws IOException {
        User user=(User)request.getSession().getAttribute("admin");
        if (user == null) {
            response.sendRedirect("adminservlet?method=login");
        }
        List<User> userList=adminService.getUserList();
        Object json = JSON.toJSON(userList);
        response.getWriter().print(json);

    }
    public void  getinvalidUserList(HttpServletRequest request,HttpServletResponse response) throws IOException {
        User user=(User)request.getSession().getAttribute("admin");
        if (user == null) {
            response.sendRedirect("adminservlet?method=login");
        }
        List<User> userList=adminService.getinvalidUserList();
        Object json = JSON.toJSON(userList);
        response.getWriter().print(json);

    }
    //删除用户
    public void  delUser(HttpServletRequest request,HttpServletResponse response) throws IOException {
        User user=(User)request.getSession().getAttribute("admin");
        if (user == null) {
            response.sendRedirect("adminservlet?method=login");
        }
        String id = request.getParameter("id");
        adminService.delUser(id);
    }
    //冻结用户
    public void  loseUser(HttpServletRequest request,HttpServletResponse response) throws IOException {
        User user=(User)request.getSession().getAttribute("admin");
        if (user == null) {
            response.sendRedirect("adminservlet?method=login");
        }
        String id = request.getParameter("id");
        adminService.loseUser(id);
    }
    //激活用户
    public void  activateUser(HttpServletRequest request,HttpServletResponse response) throws IOException {
        User user=(User)request.getSession().getAttribute("admin");
        if (user == null) {
            response.sendRedirect("adminservlet?method=login");
        }
        String id = request.getParameter("id");
        adminService.activateUser(id);
    }
    public void  searchUser(HttpServletRequest request,HttpServletResponse response) throws IOException {
        User user=(User)request.getSession().getAttribute("admin");
        if (user == null) {
            response.sendRedirect("adminservlet?method=login");
        }
        String username = request.getParameter("username");
        String gender = request.getParameter("gender");
        StringBuilder where=new StringBuilder("where 1=1");
        List<Object> params=new ArrayList<Object>();
        if(!StringUtils.isEmpty(username)){
            where.append(" and username like ?");
            params.add("%"+username+"%");
        }
        if(!StringUtils.isEmpty(gender)){
            where.append(" and gender like ?");
            params.add("%"+gender+"%");
        }
        List<User> userList= adminService.findByUsernameAndGender(where.toString(),params);
        if(userList==null||userList.size()==0){
            response.getWriter().print(0);
        }else{
            Object json = JSON.toJSON(userList);
            response.getWriter().print(json);
        }
    }
    public void  searchinvalidUser(HttpServletRequest request,HttpServletResponse response) throws IOException {
        User user=(User)request.getSession().getAttribute("admin");
        if (user == null) {
            response.sendRedirect("adminservlet?method=login");
        }
        String username = request.getParameter("username");
        String gender = request.getParameter("gender");
        StringBuilder where=new StringBuilder("where 1=1");
        List<Object> params=new ArrayList<Object>();
        if(!StringUtils.isEmpty(username)){
            where.append(" and username like ?");
            params.add("%"+username+"%");
        }
        if(!StringUtils.isEmpty(gender)){
            where.append(" and gender like ?");
            params.add("%"+gender+"%");
        }
        List<User> userList= adminService.findinvalidUserByUsernameAndGender(where.toString(),params);
        if(userList==null||userList.size()==0){
            response.getWriter().print(0);
        }else{
            Object json = JSON.toJSON(userList);
            response.getWriter().print(json);
        }
    }
    public String GoodsType(HttpServletRequest request,HttpServletResponse response) throws IOException {
        User user=(User)request.getSession().getAttribute("admin");
        if (user == null) {
            response.sendRedirect("adminservlet?method=login");
        }
        String flag = request.getParameter("flag");
        if(StringUtils.isEmpty(flag)){
            return "redirect:/admin/admin.jsp";
        }
        List<GoodsType> goodsTypeList= goodsTypeService.findAllGoodsType();
        request.setAttribute("goodsTypeList",goodsTypeList);
        if("show".equalsIgnoreCase(flag)){
            return "forward:/admin/showGoodsType.jsp";
        }else {
            return "forward:/admin/addGoodsType.jsp";
        }

    }
    public String addGoodsType(HttpServletRequest request,HttpServletResponse response) throws IOException {
        User user=(User)request.getSession().getAttribute("admin");
        if (user == null) {
            response.sendRedirect("adminservlet?method=login");
        }
        String goodsParent = request.getParameter("goodsParent");
        String typename = request.getParameter("typename");
        GoodsType goodsTypefather = goodsTypeService.findById(Integer.parseInt(goodsParent));
        GoodsType goodsType=new GoodsType();
        goodsType.setParent(goodsTypefather.getId());
        goodsType.setName(typename);
        goodsType.setLevel(goodsTypefather.getLevel()+1);
        goodsTypeService.addGoodsType(goodsType);
        return "forward:/adminservlet?method=GoodsType&flag=show";

    }
    public String getGoodsList(HttpServletRequest request,HttpServletResponse response) throws IOException {
        User user=(User)request.getSession().getAttribute("admin");
        if (user == null) {
            response.sendRedirect("adminservlet?method=login");
        }
        List<Goods> goodsList=goodsService.findAllGoods();
        request.setAttribute("goodsList",goodsList);
        return "forward:/admin/showGoods.jsp";

    }
    public String addGoods(HttpServletRequest request,HttpServletResponse response) throws IOException, ParseException, ServletException {
        User user=(User)request.getSession().getAttribute("admin");
        if (user == null) {
            response.sendRedirect("adminservlet?method=login");
        }
        String name = request.getParameter("name");
        String typeid = request.getParameter("typeid");
        String pubdate = request.getParameter("pubdate");
        String price = request.getParameter("price");
        String star = request.getParameter("star");
        String intro = request.getParameter("intro");
        Part picture = request.getPart("picture");
        List<String> nameList=new ArrayList<String>();
        nameList.add(".jpg");
        nameList.add(".png");
        nameList.add(".bmp");
        String basePath = this.getServletContext().getRealPath("WEB-INF/pictures");
        File dir=new File(basePath);
        if(!dir.exists()){
            dir.mkdirs();//创建上传目录
        }
        //修改代码2：处理IE浏览器路径问题
        String dis = picture.getHeader("Content-Disposition");// form-data; name="photo1"; filename="101.jpg"
        String filename = dis.substring(dis.lastIndexOf("filename=") + 10, dis.length() - 1);//101.jpg
        filename=filename.substring(filename.lastIndexOf("\\")+1);//c://bookcover/101.jpg
        //修改代码4：获取文件扩展名
        String exs = filename.substring(filename.lastIndexOf(".") + 1);//获取jpg
        if(!nameList.contains("."+exs)){
            return "forward:/adminservlet?method=getGoodsList";
        }

        //修改代码5；生成新的文件名
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String newFilename=uuid+"."+exs;
        //修改代码6：完成文件上传
        if(!StringUtils.isEmpty(filename)){
            //保存文件
            picture.write(basePath+File.separator+newFilename);
            //删除临时文件
            picture.delete();
        }
        Goods goods=new Goods();
        goods.setName(name);
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
        goods.setPubdate(sdf.parse(pubdate));
        goods.setPicture(newFilename);
        goods.setPrice(Double.parseDouble(price));
        goods.setStar(Integer.parseInt(star));
        goods.setIntro(intro);
        goods.setTypeid(Integer.parseInt(typeid));
        goodsService.AddGoods(goods);
        return "forward:/adminservlet?method=getGoodsList";
    }
    public String getAllOrder(HttpServletRequest request,HttpServletResponse response) throws IOException {
        User user=(User)request.getSession().getAttribute("admin");
        if (user == null) {
            response.sendRedirect("adminservlet?method=login");
        }
        List<Order> orderList=orderService.findAllOrder();
        request.setAttribute("orderList",orderList);
        return "forward:/admin/showAllOrder.jsp";

    }
    public String sendOrder(HttpServletRequest request,HttpServletResponse response) throws IOException {
        User user=(User)request.getSession().getAttribute("admin");
        if (user == null) {
            response.sendRedirect("adminservlet?method=login");
        }
        String oid = request.getParameter("oid");
        orderService.changestatus(oid);
        return "forward:/adminservlet?method=getAllOrder";
    }
    public String  searchOrder(HttpServletRequest request,HttpServletResponse response) throws IOException {
        User user = (User) request.getSession().getAttribute("admin");
        if (user == null) {
            response.sendRedirect("adminservlet?method=login");
        }
        String username = request.getParameter("username");
        String status = request.getParameter("status");
        List<Order> orderList = new ArrayList<>();
        if (StringUtils.isEmpty(username) && StringUtils.isEmpty(status)) {
            return "forward:/adminservlet?method=getAllOrder";
        } else if (!StringUtils.isEmpty(username) && StringUtils.isEmpty(status)) {

            List<User> userList = userService.findUserByUsername(username);

            if (userList != null && userList.size() > 0) {
                for (User user1 : userList) {
                    List<Order> orders = orderService.searchOrderByUid(user1.getId());
                    if(orders!=null&&orders.size()>0){
                        for (Order order : orders) {
                            orderList.add(order);
                        }
                    }

                }
            }
        }else if(StringUtils.isEmpty(username) && !StringUtils.isEmpty(status)){
            orderList=orderService.searchOrderByStatus(status);
        }else {
            List<User> userList = userService.findUserByUsername(username);
            if (userList != null && userList.size() > 0) {
                for (User user1 : userList) {
                    List<Order> orders = orderService.searchOrderByUidAndStatus(user1.getId(),status);
                    for (Order order : orders) {
                        orderList.add(order);
                    }

                }
            }
        }

        request.setAttribute("orderList",orderList);
        return "forward:/admin/showAllOrder.jsp";
    }
    public String  searchGoodsType(HttpServletRequest request,HttpServletResponse response) throws IOException {
        User user = (User) request.getSession().getAttribute("admin");
        if (user == null) {
            response.sendRedirect("adminservlet?method=login");
        }
        String level = request.getParameter("level");
        String name = request.getParameter("name");
        List<GoodsType> goodsTypeList = new ArrayList<>();
        if (StringUtils.isEmpty(name) && StringUtils.isEmpty(level)) {
            return "forward:/adminservlet?method=GoodsType&flag=show";
        } else if (!StringUtils.isEmpty(level) && StringUtils.isEmpty(name)) {

            goodsTypeList= goodsTypeService.findGoodsTypeByLevel(level);


        }else if(StringUtils.isEmpty(level) && !StringUtils.isEmpty(name)){
            goodsTypeList= goodsTypeService.findGoodsTypeByName(name);
        }else {
            goodsTypeList= goodsTypeService.findGoodsTypeByNameAndLevel(level,name);
        }

        request.setAttribute("goodsTypeList",goodsTypeList);
        return "forward:/admin/showGoodsType.jsp";
    }
}
